﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;
using System.Windows.Media.Imaging;
using FinPlusInterfaces;
using FinPlusAssembler;

namespace FinPlusCompView
{
    public sealed class FinPlusMenuItem:FinPlusControl
    {
        [State(Test = true)]
        public override bool IsValid { get; set; }
        public MenuItem MenuItem { get; private set; }
 
        private object _placement;
        private readonly string _query, _view;
        private FinPlusWindow _window;
        private static ResourceDictionary _images;

        //construct
        public FinPlusMenuItem(string header, string icon, string view, string query = "", IFinPlusComp[] menuItems = null)
        {
            MenuItem = new MenuItem();
            _query = query;
            _view = view;
            AddIcon(icon);

            if (!string.IsNullOrEmpty(header))  
                MenuItem.Header = header;
            
            MenuItem.Click += MenuItem_Click;

            if(menuItems != null)
                foreach(FinPlusMenuItem menuItem in menuItems)
                    MenuItem.Items.Add(menuItem.MenuItem);

            IsValid = true;
        }
   
        //common control interface 
        public override void CmdExecute(IPod command)
        {
            try
            {
                CmdCapture(command);

                switch ((Cmds)Enum.Parse(typeof(Cmds), command.Name, true))
                {
                    case Cmds.ExecuteAction: ExecuteAction(); break;
                    default: throw new Exception(string.Format("cmd not recognised {0}", command.Name));
                }
            }
            catch (CmdExecuteException e)
            {
                IsValid = Level.Error.Log(Id, Config, e.Message, e);
            }
        }

        //private
        private void ExecuteAction()
        {
            if (_placement == null) 
                _placement = Target();

            if (_window == null) 
                _window = ((DataGrid)_placement).FindVisualParent<FinPlusWindow>();

            switch (_view.EnumParse<MenuAction>(MenuAction.Default))
            {
                case MenuAction.Clone: IOC.Singleton<IWindowHelper>().OpenAsync(Paths.Values["FolderSubViews"] + "PodEditor", "PodEditor", new object[,] { { "Pod", Underlying().Clone(-1) } }, Env, ShowType.Dispatch, "", "", true); break;
                case MenuAction.Edit: IOC.Singleton<IWindowHelper>().OpenAsync(Paths.Values["FolderSubViews"] + "PodEditor", "PodEditor", new object[,] { { "Pod", Underlying() } }, Env, ShowType.Dispatch, "", "", true); break;
                case MenuAction.Copy: ApplicationCommands.Copy.Execute(null, (DataGrid)_placement); break;
                case MenuAction.Print: new PrintDialog().PrintVisual((DataGrid)_placement, "Printing"); break;
                case MenuAction.None: break;
                case MenuAction.Default: OpenWindow(); break;
            }
        }

        private object Target()
        {
           var res = MenuItem.Parent;
           do
           {
               if (res.GetType().Equals(typeof(MenuItem)))
                   res = ((MenuItem)res).Parent;
               else
               {
                   if (res.GetType().IsTypeOf<ContextMenu>())
                       return ((ContextMenu)res).PlacementTarget;
                   return ((Menu)res).Parent;
               }

           }
           while(true);
        }

        private IPod Underlying()
        {
            return ((IDPod)((DataGrid)_placement).CurrentItem).ToPod();
        }

        private void AddIcon(string icon)
        {
            if (_images == null)
                _images = new ResourceDictionary { Source = new Uri("pack://application:,,,/FinPlusCompView;component/Resource.Images.xaml", UriKind.RelativeOrAbsolute) };

            if (!string.IsNullOrEmpty(icon))
                MenuItem.Icon =  new Image { Source = (BitmapImage)_images[icon] };
        }

        private void OpenWindow()
        {
            IOC.Singleton<IWindowHelper>().OpenProcess(Paths.Values["FolderSubViews"] + _view, _view, Env, ShowType.Show, LinkedId, Underlying().Replace(_query), true);
        }

        //cmds
        private enum Cmds { ExecuteAction }

        //events
        private void MenuItem_Click(object s, RoutedEventArgs a) {CmdRouter(Cmds.ExecuteAction.ToString());}
    }
}


























































































//Copyright2013<jnrton>AllRightsReserved 
//Contact j.nrton@finpus